Sail.widget.ext.ux_itemselector = function(config) {
	this.option = config || {};
	Sail.widget.ext.ux_itemselector.superclass.constructor.call(this, config);
};

Ext.extend(Sail.widget.ext.ux_itemselector, Sail.widget, {
	from_url: "",
	to_url: "",
	from_root: "",
	from_id: "id",
	from_text: "name",
	to_root: "",
	to_id: "id",
	to_text: "name",

	to_filter_field: '',
	to_filter_value: '',
	is_filter: true,
    to_same_root : false,
	// for filter_for_toMul
	imagePath: '../../../support/multiselect/',

	//for simplestore
	dataFields: ['id', 'name'],
	valueField: 'id',
	displayField: 'name',

	defaultHeight: 300,
	defaultWidth: 400,
	enableBindData: true,
	initComponent: function() {},
	getHeight: function() {
		return this.height || this.defaultHeight;
	},
	setHeight: function(height) {
		this.getOCD().style.height = height || this.getHeight();
	},
	getWidth: function() {
		return this.width || this.defaultWidth;
	},
	setWidth: function(width) {
		this.getOCD().style.width = width || this.getWidth();
	},
	getEl: function() {
		return this.el;
	},
	getSubObj: function(fo, subs) {
		try {
			if (!subs) return null;
			if (typeof subs == "string") {
				subs = subs.split(".");
			}
			if (subs.length === 1) return fo[subs[0]];
			var pp = (subs[0].indexOf("[") === - 1) ? "": subs[0].split("[")[1].replace("]", "");
			fo = (subs[0].indexOf("[") === - 1) ? fo[subs[0]] : fo[subs[0].split("[")[0]][pp];
			subs.splice(0, 1);
			return Sail.getSubObj(fo, subs);
		} catch(e) {
			return null;
		}
	},
    copy_attr_json : function(rs,root,v){
        try{
            if(!rs || !root || !v) return;
            if(typeof root == 'string') root = root.split(".");
            if(root.length === 1){ rs[root[0]] = v; return;}
            var t = (root[0].indexOf['['] === -1 ? true : false);
            var p = t ?  '' : root[0].split["["][1].replace("]","");
            rs = t ? rs[root[0]] : rs[root[0].split("[")[0]][pp];
            root.splice(0,1);
            copy_attr_json(rs,root,v);
        } catch(e){ return ; }
    },
	/*保存时额外调用的方法 一般情况下需要重写　能否做到通用？*/
	update_business: function() {
		var rs = this.ownerFrame.businessData || {};
		var f_s = this.el.fromMultiselect.view.store;
		var t_s = this.el.toMultiselect.view.store;

		var f_d = this.getSubObj(rs, this.from_root);
		var t_d = this.getSubObj(rs, this.to_root);

		/*一般情况下，fromMultiselect 的数据不需要保存*/
		if (f_d) { (f_d instanceof Array) ? f_d.length = 0: null;
			f_s.each(function(r) {
				if (f_d.push) {
					f_d.push(r.data);
				} else {
					f_d[this.from_id] = r.get(this.dataFields[0]);
					f_d[this.from_text] = r.get(this.dataFields[1]);
				}
			},
			this);
		}

		if (t_d) { 
            (t_d instanceof Array) ? t_d.length = 0: null;
            var i = 0;
			t_s.each(function(r) {
				if (t_d.push) {
                    t_d[i][this.from_id] = r.get(this.dataFields[0]); 
                    t_d[i][this.from_text] = r.get(this.dataFields[1]); 
					if (this.to_filter_field) 
                        t_d[i][this.to_filter_field] = this.to_filter_value;
                    i++;
				} else {
					t_d[this.from_id] = r.get(this.dataFields[0]);
					t_d[this.from_text] = r.get(this.dataFields[1]);
					if (this.to_filter_field) t_d[this.to_filter_field] = this.to_filter_value;
				}
			},
			this);
		}

	},
	bindData: function(rs) {
		if (!rs) {
			rs = this.ownerFrame.businessData;
		}
		if (this.from_url && this.to_url) return;

		var f_json, t_json;
		if (this.from_root && !this.from_url) f_json = this.getSubObj(rs, this.from_root);
		if (this.to_root && !this.to_url) t_json = this.getSubObj(rs, this.to_root);
		this.refresh(f_json, t_json);
	},
	refresh: function(f_json, t_json) {
		var f_data = [];
		var t_data = [];
		if (!f_json && ! t_json) return;
		if (f_json) {
			f_json = [].concat(f_json);
			for (var i = 0; i < f_json.length; i++) {
				f_data.push([f_json[i][this.from_id], f_json[i][this.from_text]]);
			}
		}
		if (t_json) {
			t_json = [].concat(t_json);
			for (var j = 0; j < t_json.length; j++) {
				if (this.to_filter_field) {
					/*处理针对如果存在多个itemselector 组件，而且绑定数据来源于同一级数据结构，只用一个属性(flag=1)来区分的情况．目前只考虑了右边的multiselect［待测试］*/
					if (! (t_json[j][this.to_filter_field] === this.to_filter_value)) continue;
				}
				t_data.push([t_json[j][this.to_id], t_json[j][this.to_text]]);
			}
		}

		if (f_data.length > 0) {
			var f_store = new Ext.data.SimpleStore({
				fields: this.dataFields,
				data: f_data
			});
            this.el.fromMultiselect.store = f_store;
			this.el.fromMultiselect.view.setStore(f_store);
		}
		if (t_data.length > 0) {
			var t_store = new Ext.data.SimpleStore({
				fields: this.dataFields,
				data: t_data
			});
			//this.filter_for_toMul(); // bad luck for ajax request time. fromMultiselect loading data and toMultiselect bindData who will be the  first. 
            this.el.toMultiselect.store = t_store;
			this.el.toMultiselect.view.setStore(t_store);
		}
	},
	//
	filter_for_toMul: function() {
		if (!this.is_filter) return;
		var f = this.el.fromMultiselect.view.store;
		var s = this.el.toMultiselect.view.store;
		f.filterBy(function(r) {
			if (s.find('id',r.data['id']) > -1 || r.get('id') === '') return false;
			else return true;
		},
		this);
	},
	init_config: function() {
		if (this.from_url !== "") {
			this.fromStore = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: this.from_url,
					method: "POST"
				}),
				reader: new Ext.data.JsonReader({
					root: this.from_root
				},
				[this.from_id, this.from_text])
			});
		}
		this.fromStore.load({
			callback: function() {
				/*
             * Important: loading is asynchronous! This call will return before the new data has been loaded. To perform any post-processing where information from the load call is required, specify the callback function to be called, or use a a 'load' event handler.*/
				this.filter_for_toMul();
			},
			scope: this
		});

		if (this.to_url !== "") {
			this.toStore = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: this.to_url,
					method: "POST"
				}),
				reader: new Ext.data.JsonReader({
					root: this.to_root
				},
				[this.to_id, this.to_text])
			});
			this.toStore.load({
				callback: function() {
					// may by no recrod in fromstore for ajax request time this is a bug . this is need a test case
					this.filter_for_toMul();
				},
				scope: this
			});
		}
	},
	createWidgetElement: function() {
		this.init_config();
		Ext.apply(this.option, {
			dataFields: this.dataFields,
			valueField: this.valueField,
			displayField: this.displayField,
			toData: this.toData || [],
			fromData: this.fromData || [],
			fromStore: this.fromStore || null,
			imagePath: this.imagePath,
            msHeight : this.height,
			toStore: this.toStore || null
		});
		this.el = new Ext.ux.ItemSelector(this.option);
		this.el.render(this.getOCD());
	}
});

